package com.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.service.impl.PomrsDownService;
import com.service.impl.PomrsUploadService;
import com.utils.Ret;
import com.utils.report.ExcelTsPrintByPOI;

@Controller
public class ReportController {
	
	@Autowired
	PomrsDownService pomrsDownService;
	
	@Autowired
	PomrsUploadService pomrUploadService;
	
	@RequestMapping("downPorms.do")
	public void downPorms(HttpServletRequest request,HttpServletResponse response,
			@RequestParam("abpath") String abpath,
			@RequestParam("ocode")String ocode){
	
		try{ 
			if(!abpath.endsWith(File.separator)){
				abpath=abpath+File.separator;
			}
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			Calendar cal = Calendar.getInstance();
			String fileName="居民健康档案"+".xls";
			fileName=new String(fileName.getBytes("GBK"),"ISO8859-1");
			response.setHeader("Content-Disposition", "filename="+fileName+"");

			OutputStream os = response.getOutputStream();
			String templatepath = abpath+"DWZ"+File.separator+"examples"+File.separatorChar+ "pomrs_downlaod.xls";
			pomrsDownService.setOut(os);
			pomrsDownService.setRequest(request);
			if("0".equals(ocode)){
				ocode="";
			}
			pomrsDownService.setOcode(ocode);
			
			ExcelTsPrintByPOI print = new ExcelTsPrintByPOI(os,templatepath,pomrsDownService);
			os = print.tsPrint();
			
			
			os.flush();
			os.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	
	}
	
	@RequestMapping("toUploadPomrs.do")
	public String toUploadPomrs(){
		return "report/toUploadPomrs";
	}
	/*	
	@RequestMapping("doUploadPomrs.do")
	public void doUploadPomrs(HttpServletRequest request,Ret ret,PrintWriter out,
			@RequestParam("ocode") String ocode,
			@RequestParam("dir") String dir,
			@RequestParam("savePath")String savePath,@RequestParam MultipartFile upfile){
			
		request.setAttribute("ocode", ocode);
		request.setAttribute("upfile", upfile);
		request.setAttribute("dir", dir);
		request.setAttribute("savePath", savePath);

		FileUpload fu = new FileUpload(request,savePath);
		fu.upload();

		//数据导入
		String filepath = fu.getSavePath();
		
		pomrUploadService.setOcode(ocode);
		pomrUploadService.setMaxcount(10000);//设置最大上传行
		pomrUploadService.setFu(fu);
		pomrUploadService.setRequest(request);
		

		String upload_way = pomrUploadService.getFu().getParams().get("SQL_MODE");//获取表单参数从这里获取
		pomrUploadService.setUpload_sets(upload_way);

		pomrUploadService.upload();

		ret.setMessage(pomrUploadService.returnmsg());

		out.print(ret.toJsonString());
		out.flush();
		out.close();
	}

	
	
	
	@SuppressWarnings("deprecation")
	@RequestMapping("doUploadPomrs.do")
	  public void importBrandSort(@RequestParam("upfile") MultipartFile file,
	      HttpServletRequest request,HttpServletResponse response) throws Exception {
		
	    String saveDire = request.getSession().getServletContext()
	        .getRealPath(File.separator)
	        + "DEZ/attached"; // 临时目录
	    File tempFile = new File(saveDire);
	    if (!tempFile.exists()) {
	      tempFile.mkdirs();
	    }
	    DiskFileUpload fu = new DiskFileUpload();
	    fu.setSizeMax(10 * 1024 * 1024); // 设置允许用户上传文件大小,单位:位
	    fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:位
	    fu.setRepositoryPath(saveDire); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
	    // 开始读取上传信息
	    int index = 0;
	 	List fileItems = null;
	    try {
	      fileItems = fu.parseRequest(request);
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	    
	    Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
	    FileItem fileItem = null;
	    while (iter.hasNext()) {
	      FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
	      if (!item.isFormField()) {
	        fileItem = item;
	        index++;
	      }
	    }
	    
	    String name = file.getOriginalFilename();// 获取上传文件名,包括路径
	    //name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
	    long size = file.getSize();
	    InputStream in = file.getInputStream();
	    String strAlertMsg ="";
	    //request.setAttribute("brandPeriodSortList", BrandMobileInfos);
	    //request.setAttribute("strAlertMsg", strAlertMsg);
	  
	    request.getSession().setAttribute("msg",strAlertMsg);
	    //return null;
	  }
	*/
	@RequestMapping(value = "doUploadPomrs.do", method = RequestMethod.POST)
    public void batchimport(@RequestParam(value="upfile") MultipartFile file,
            HttpServletRequest request,HttpServletResponse response,
            Ret ret,PrintWriter out,@RequestParam("ocode") String ocode) throws IOException{
		
        //判断文件是否为空
		try {
			if(file==null){
	        	ret.setStatusCode("300");
	        	ret.setMessage("");
	        }else{
	        	//获取文件名
	            String name=file.getOriginalFilename();
	            //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
	            long size=file.getSize();
	            if(name==null || ("").equals(name) && size==0) {
	            	ret.setStatusCode("300");
	            	ret.setMessage("");
	            }
	            
	            //批量导入。参数：文件名，文件。
	            pomrUploadService.setOcode(ocode); 
	            int ocode1 = Integer.parseInt(request.getSession().getAttribute("ocode").toString());
	            boolean b = pomrUploadService.batchImport(name,file,ocode1);
	            if(b){
	                 ret.setMessage("批量导入EXCEL成功！");
	                 ret.setCallbackType("200"); 
	            }else{
	            	ret.setStatusCode("300");
	            	ret.setMessage("批量导入EXCEL失败！");
	            } 
	        }
		} catch (Exception e) {
			ret.setStatusCode("300");
        	ret.setMessage("批量导入EXCEL失败！");
		}
        out.print(ret.toJsonString());
		out.flush();
		out.close();
    }
}
